package com.example.k12.utlis.db

import com.example.k12.app.MyApp
import android.database.sqlite.SQLiteDatabase
import com.example.k12.bean.DaoMaster
import com.example.k12.bean.DaoSession
import com.example.k12.bean.StudentInfo
import com.example.k12.bean.StudentInfoDao


/**
 * GreenDao数据库管理类
 * 不依赖Context的数据库管理器
 */
class DBManager private constructor() {

    private lateinit var daoSession: DaoSession
    private lateinit var studentInfoDao: StudentInfoDao

    companion object {
        @Volatile
        private var instance: DBManager? = null

        fun getInstance(): DBManager {
            return instance ?: synchronized(this) {
                instance ?: DBManager().also { instance = it }
            }
        }
    }

    /**
     * 初始化数据库（在Application中调用）
     */
    fun init() {
        val context = MyApp.getContext()
        val helper = DaoMaster.DevOpenHelper(context, "k12-db")
        val db: SQLiteDatabase = helper.writableDatabase
        val daoMaster = DaoMaster(db)
        daoSession = daoMaster.newSession()
        studentInfoDao = daoSession.studentInfoDao
    }

    /**
     * 检查数据库是否已初始化
     */
    private fun checkInitialized() {
        if (!::daoSession.isInitialized) {
            throw IllegalStateException("DBManager未初始化，请在Application中调用init()方法")
        }
    }

    /**
     * 插入或更新学生信息
     */
    fun insertOrUpdateStatisticsBean(statisticsBean: StudentInfo): Long {
        checkInitialized()
        return studentInfoDao.insertOrReplace(statisticsBean)
    }

    /**
     * 根据学生ID查询学生信息
     */
    fun queryStatisticsBeanById(statisticsBeanId: String): StudentInfo? {
        checkInitialized()
        return studentInfoDao.queryBuilder()
            .where(StudentInfoDao.Properties.Uuid.eq(statisticsBeanId))
            .unique()
    }

    /**
     * 查询所有学生
     */
    fun queryAllStatisticsBeans(): List<StudentInfo> {
        checkInitialized()
        return studentInfoDao.queryBuilder().list()
    }

    /**
     * 删除学生信息
     */
    fun deleteStatisticsBean(statisticsBean: StudentInfo) {
        checkInitialized()
        studentInfoDao.delete(statisticsBean)
    }

    /**
     * 批量插入学生信息
     */
    fun insertStatisticsBeans(statisticsBeans: List<StudentInfo>) {
        checkInitialized()
        studentInfoDao.insertOrReplaceInTx(statisticsBeans)
    }

    /**
     * 更新学生余额
     */
    fun updateStatisticsBeanBalance(statisticsBeanId: String, newBalance: Double) {
        checkInitialized()
        val statisticsBean = queryStatisticsBeanById(statisticsBeanId)
        statisticsBean?.let {
            it.balance = newBalance
            it.consumeCount +=1
            studentInfoDao.update(it)
        }
    }

    /**
     * 清空所有数据（谨慎使用）
     */
    fun clearAllData() {
        checkInitialized()
        studentInfoDao.deleteAll()
    }
}
